package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.dao.UserInfoDao;
import com.hqyj.pojo.MyNode;
import com.hqyj.pojo.ResultVo;
import com.hqyj.pojo.UserInfo;
import com.hqyj.service.UserInfoService;
import com.hqyj.util.MdFive;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Autor 伍军
 * @Date 2022/9/8 16:09
 * @Version 1.0
 **/
@Service
public class UserInfoServiceImpl implements UserInfoService {

    //注入邮件发送服务类
    @Autowired
    JavaMailSender javaMailSender;

    //获取发件人邮箱
    @Value("${spring.mail.username}")
    String sendEmail;

    @Autowired
    MdFive mdFive;

    @Resource
    UserInfoDao userInfoDao;
     //注入 redis
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    //注入短信发送服务对象
    @Autowired
    SmsClient smsClient;

    @Override
    public ResultVo sendCode(String email) {
        ResultVo rv = new ResultVo();
        try{
            //创建邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            //定义收件人邮箱
            message.setTo(email);
            //定义发送人邮箱
            message.setFrom(sendEmail);
            //定义邮件标题
            message.setSubject("xxx公司验证码");
            //定义邮件正文
            Random rd = new Random();
            int code = rd.nextInt(10000);
            message.setText("你的验证码是:"+code);
            //发送邮件
            javaMailSender.send(message);
            System.out.println("发送成功");
            rv.setSuccess(true);
            rv.setInfo("发送成功");
            //定义redis键名
            String key = "code:"+email;
            //存入验证码，并设置失效时间1 分钟
            redisTemplate.opsForValue().set(key,code+"",1, TimeUnit.MINUTES);

        }catch (Exception e){
            e.printStackTrace();
            System.err.println("发送失败");
            rv.setInfo("发送失败");
        }

        return rv;
    }

    @Override
    public ResultVo validateCode(UserInfo user) {
        ResultVo rv = new ResultVo();
        //判断验证码是否失效
        //定义redis键名
        String key = "code:"+user.getEmail();
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            rv.setInfo("验证码失效");
        }else{
            if(user.getCode().equals(obj)){
                rv.setInfo("输入正确");
                rv.setSuccess(true);
            }else{
                rv.setInfo("验证码输入不正确");
            }
        }
        return rv;
    }

    @Override
    public ResultVo updatePwd(UserInfo user) {
        ResultVo rv = new ResultVo();
        //生成盐值
        String salt = UUID.randomUUID()+"";
        //记录盐值
        user.setSalt(salt);
        //生成加密的字符串
        String pwd = mdFive.encrypt(user.getUserPwd(),salt);
        //记录加密字符串
        user.setUserPwd(pwd);

        //创建条件构造器
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //定义邮箱条件
        queryWrapper.eq("email",user.getEmail());

        int num =userInfoDao.update(user,queryWrapper);
        if(num>0){
            rv.setSuccess(true);
            rv.setInfo("修改成功");
        }else{
            rv.setInfo("修改失败");
        }

        return rv;
    }

    @Override
    public ResultVo sendSms(String phone) {
        ResultVo rv = new ResultVo();
        //创建短信发送对象
        SendSmsRequest request = new SendSmsRequest();
        //设置接收人电话
        String p[] ={phone};
        request.setPhoneNumberSet(p);
        //设置短信模板Id
        request.setTemplateId("1259138");
        //设置短信发送SDK
        request.setSmsSdkAppId("1400372925");
        //设置签名
        request.setSignName("阳光云公众号");
        //设置发送验证码
        Random rd = new Random();
        int code = rd.nextInt(10000);
        String c[] = {code+""};
        request.setTemplateParamSet(c);

        try {
            //发送短信,获取响应值
            SendSmsResponse rs =smsClient.SendSms(request);
            //打印
            System.out.println(SendSmsResponse.toJsonString(rs));
            System.out.println("发送完毕");
            //把响应对象的json格式的字符串转成java的Map数据类型
            ObjectMapper mapper = new ObjectMapper();
            //转换
            Map<String,Object> map = mapper.readValue(SendSmsResponse.toJsonString(rs),Map.class);

            ArrayList<LinkedHashMap<String,Object>> list =(ArrayList<LinkedHashMap<String,Object>>) map.get("SendStatusSet");
            if(list.get(0).get("Code").equals("Ok")){
                rv.setSuccess(true);
                rv.setInfo("发送成功");
            }else{
                rv.setInfo("发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rv;
    }

    @Override
    public ResultVo queryPowerByName(String userName) {
        ResultVo rv = new ResultVo();
        //查询权限
        List<MyNode> nodeList = userInfoDao.queryPowerByName(userName);
        //创建一个构建好树形节点的集合
        List<MyNode> newList = new LinkedList<>();
        //构建树形数据结构
        if(nodeList.size()>0){
            //遍历权限集合
            for(MyNode myNode:nodeList){
                //查找一级菜单
                if(myNode.getParentId()==0){
                    //创建一级菜单的子菜单集合对象
                    List<MyNode> childRenList = new LinkedList<>();
                    //查找一级菜单的子菜单
                    for(MyNode n:nodeList ){
                        if(n.getParentId()==myNode.getNodeId()){
                            //添加子菜单
                            childRenList.add(n);
                        }
                    }
                    //设置子菜单到一级菜单红
                    myNode.setChildren(childRenList);
                    //添加树形节点
                    newList.add(myNode);
                }

            }
            rv.setSuccess(true);
            rv.setData(newList);
        }
        return rv;
    }
}
